package gw.com.android.ui.bulletin;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.greendao.NotifyDataHelper;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.ui.BaseActivity;
import gw.com.android.utils.OpenApi;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.ThreadPool;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.CommonUtils;
import www.com.library.util.DoubleConverter;
import www.com.library.util.StringFormatter;
import www.com.library.util.StringUtils;
import www.com.library.view.BtnClickListener;

/**
 * 消息详情 openApi
 *
 * @author aries
 */
public class BulletinDetailActivity2 extends BaseActivity {

    @BindView(R.id.ll_content)
    View mContentLayout;
    @BindView(R.id.news_subject)
    TextView mTitleSubView;
    @BindView(R.id.news_time)
    TextView mTitleTimeView;
    @BindView(R.id.loading_progress_view)
    View mProgressView;
    @BindView(R.id.error_layout)
    View mErrorView;
    private String mDataId;
    private String extend;
    private int formType = AppContances.TYPE_FORM_BULLETIN;//标识从哪个界面过来，默认从消息中心过来
    private final int NEWS_DETAIL = 1;
    private final int URL_NEWS_DETAIL = 2;
    private int pageType = NEWS_DETAIL;
    private ConfigSettingDeal mSettingDeal;
    private OpenApi openApi = null;
    private BulletinWebFragment webFragment;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_message_detail2;
    }

    @Override
    protected void initLayoutView() {
        mDataId = getIntent().getStringExtra("mDataId");
        //通知栏扩展字段。列表进入该值为null
        extend = getIntent().getStringExtra("extend");
        formType = getIntent().getIntExtra("fromType", AppContances.TYPE_FORM_BULLETIN);

        mTitleBar.setAppTitle(AppMain.getAppString(R.string.system_notice_detail));
        mTitleBar.setBtnClickListener(new BtnClickListener() {
            @Override
            public void onBtnClick(int viewID) {
                if (viewID == R.id.title_left_icon) {
                    onBackPressed();
                }
            }
        });
    }

    @Override
    protected void initViewData() {
        mSettingDeal = new ConfigSettingDeal();
        mProgressView.setVisibility(View.VISIBLE);
        mContentLayout.setVisibility(View.GONE);
        openApi = new OpenApi();
        loadData();
    }

    /**
     * 加载数据
     */
    private void loadData() {
        String messageType;
        if (formType == AppContances.TYPE_FORM_BULLETIN) {
            messageType = OpenApi.CLICK_PUSH_DETAIL_CENTERLIST;
        } else {
            messageType = OpenApi.CLICK_PUSH_DETAIL_NOTICEBOARD;
        }
        openApi.getPushInfoDetail(mDataId, messageType, extend, new HttpCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject resultJsonObj = new JSONObject(result).getJSONObject("data");
                    String link = resultJsonObj.getString("link");
                    long detailId = resultJsonObj.optLong("detailId", -1);
                    if (StringUtils.isEmpty(link)) {
                        pageType = NEWS_DETAIL;
                        Logger.e("消息详情数据返回成功2");
                        mProgressView.setVisibility(View.GONE);
                        mErrorView.setVisibility(View.GONE);
                        mContentLayout.setVisibility(View.VISIBLE);
                        mTitleSubView.setText(resultJsonObj.optString("title"));
                        String ctime = resultJsonObj.optString("ctime");
                        mTitleTimeView.setText(StringFormatter.instance().secToDateTimeHM(DoubleConverter.toLongData(ctime)));
                        StringBuilder htmlbuf = new StringBuilder();
                        htmlbuf.append("<html><head><meta name='viewport' content='width=device-width, initial-scale=1.0' />");
                        htmlbuf.append("<style type='text/css'>");
                        htmlbuf.append("img {height: auto;position: relative;width: 100%;}");
                        htmlbuf.append("</style>");
                        htmlbuf.append("</head>");
                        htmlbuf.append("<body>");
                        htmlbuf.append("<div style='font-size:15px;color:#404040;line-height:160%;word-break:break-all'>");
                        htmlbuf.append(resultJsonObj.optString("content"));
                        htmlbuf.append("</div></body><html>");
                        Bundle bundle = new Bundle();
                        bundle.putString("content", htmlbuf.toString());
                        showFragment(bundle);
                    } else {
                        pageType = URL_NEWS_DETAIL;
                        mContentLayout.setVisibility(View.GONE);
                        link = ConfigUtil.getDealStrUrl(link);
                        Bundle bundle = new Bundle();
                        bundle.putString("url", link);
                        showFragment(bundle);
                    }
                    setNotifyReaded(detailId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Exception e) {
                failDeal(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
            }
        });
    }

    private void showFragment(Bundle args) {
        webFragment = new BulletinWebFragment();
        webFragment.setArguments(args);
        webFragment.setOverrideUrlListener(new BulletinWebFragment.OverrideUrlListener() {
            @Override
            public boolean onOverride(String url) {
                if (pageType == NEWS_DETAIL) {
                    DataItemDetail item = mSettingDeal.getItemValue(AppMain.getAppString(R.string.system_notice_detail), url);
                    item.setBooleanValue(ConfigType.CONFIG_TYPE_TYPE_HASBACK_TAG, true);
                    if (url.contains(ConfigType.REPLACE_LOGIN_TOKEN_TAG) && GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_GUEST) {
                        item.setStringValue(ConfigType.CONFIG_TYPE_TYPE_TAG, ConfigType.CONFIG_TYPE_TYPE_URL_RGS_TAG);
                    }
                    ActivityManager.showWebPageActivity(BulletinDetailActivity2.this, item, AppMain.getAppString(R.string.btn_back));
                    return true;
                } else {
                    PackStatis.getToService(PackStatis.EventAction.CLICKMESSAGELINK.getValue(), PackStatis.EventCategory.MESSAGE.getValue(), null, null);
                }
                return false;
            }
        });
        showFragment(webFragment);
    }

    private void setNotifyReaded(final long id) {
        Logger.e("_notify", "setNotifyReaded detail = " + id);
        if (id == -1) {
            return;
        }
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                boolean success = NotifyDataHelper.setNotifyReaded(id);
                if (success) {
                    NotifyDataHelper.notifyChange();
                } else {
                    NotifyRequest.handlerReadedId(id);
                }
            }
        });
    }

    @OnClick(R.id.error_layout)
    public void errorClick() {
        if (CommonUtils.isFastDoubleClick()) {
            return;
        }
        if (null != mErrorView) {
            mErrorView.setVisibility(View.GONE);
        }
        if (null != mProgressView) {
            mProgressView.setVisibility(View.VISIBLE);
        }
        loadData();
    }

    /**
     * 失败处理
     */
    private void failDeal(String errorMessage) {
        mProgressView.setVisibility(View.GONE);
        mContentLayout.setVisibility(View.GONE);
        mErrorView.setVisibility(View.VISIBLE);
        showToastPopWindow(errorMessage);
    }

    @Override
    public void onBackPressed() {
        if (webFragment != null && webFragment.onBackPressed()) {
            return;
        }
        finish();
    }

}
